<template>
	<div>
		<div class="container">
			<div id="map-div"></div>
		</div>
	</div>
</template>

<script>
	export default {
		name: 'BaiduMap',
		data() {
			return {
				shopList: []
			}
		},
		mounted() {
			this.loadBaiduMap()
		},
		methods: {
			//加载百度地图
			loadBaiduMap() {
				let map = new BMap.Map("map-div");
				let point = new BMap.Point(108.365087, 22.819314);
				map.centerAndZoom(point, 10); //初始化地图，设置中心点坐标和地图级别 

				map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
				map.addControl(new BMap.GeolocationControl({
					// 定位信息面板
					showAddressBar: false
				}));
				map.addControl(new BMap.NavigationControl()); //平移缩放控件
				//绘制边界
				this.drawBorder(map)
				//添加标注
				this.doMarker(map)
			},
			//绘制边界
			drawBorder(map) {
				let bdary = new BMap.Boundary();
				//获取行政区域
				bdary.get("广西壮族自治区钦州市灵山县", (rs) => {
					// map.clearOverlays(); //清除地图覆盖物    
					let count = rs.boundaries.length; //行政区域的点有多少个
					if (count === 0) {
						alert('未能获取当前输入行政区域');
						return;
					}
					let pointArray = [];
					for (let i = 0; i < count; i++) {
						let ply = new BMap.Polygon(rs.boundaries[i], {
							fillColor: "", //填充颜色
							strokeWeight: 2, //边线的宽度
							strokeColor: "#ff0000" //边线颜色
						}); //建立多边形覆盖物
						map.addOverlay(ply); //添加覆盖物
						pointArray = pointArray.concat(ply.getPath());
					}
					map.setViewport(pointArray); //调整视野  
				});
			},
			//添加标注
			doMarker(map) {
				let _this = this
				_this.$axios({
					method: 'get',
					url: '/seller/listAllSellerOnMap'
				}).then((resp) => {
					let data = resp.data
					_this.shopList = data

					//数据返回后做标注
					for (let i = 0; i < data.length; i++) {
						let marker = new BMap.Marker(new BMap.Point(data[i].lng, data[i].lat));
						map.addOverlay(marker);

						marker.addEventListener("click", () => {
							// console.log(data[i])

							let content = `<h4 style='margin:0 0 5px 0;'>` + data[i].shopName + `</h4>
							<button id="entryShop" type="button">进入该店铺</button>`;
							// 创建信息窗口对象  
							let infoWindow = new BMap.InfoWindow(content);
							//开启信息窗口
							map.openInfoWindow(infoWindow, new BMap.Point(data[i].lng, data[i].lat));


							if (!infoWindow.isOpen()) {
								//如果没有打开，则监听打开事件，获取按钮，添加事件
								infoWindow.addEventListener("open", () => {
									document.getElementById("entryShop").onclick = (e) => {
										_this.$router.push({
											path: "/page/sellerShop",
											query: {
												id: _this.shopList[i].id
											}
										})
									};
								});
							} else {
								//如果已经打开，直接获取按钮，添加事件
								document.getElementById("entryShop").onclick = (e) => {
									_this.$router.push({
										path: "/page/sellerShop",
										query: {
											id: _this.shopList[i].id
										}
									})
								};
							}

						});
					}
				})
			}
		}
	}
</script>

<style scoped>
	.container {
		position: absolute;
		width: 100%;
		height: 94%;
	}

	#map-div {
		width: 100%;
		height: 100%;
	}
</style>
